package com.example.pda.common;

import android.graphics.Color;
import android.text.TextUtils;

//import com.kaopiz.kprogresshud.KProgressHUD;

import com.kaopiz.kprogresshud.KProgressHUD;

import java.util.Objects;

import androidx.lifecycle.Observer;

public abstract class BaseFragment extends LazyFragment {

    protected void registerObserve(BaseViewModel viewModel) {
        if (viewModel == null) return;
        viewModel.getShowDialog().observe(getViewLifecycleOwner(), new Observer<Boolean>() {
            @Override
            public void onChanged(Boolean aBoolean) {
                if (aBoolean) {
                    showLoadingDialog("");
                } else {
                    hideLoadingDialog();
                }
            }
        });
        viewModel.getDialogMsg().observe(getViewLifecycleOwner(), new Observer<String>() {
            @Override
            public void onChanged(String s) {
                if (!TextUtils.isEmpty(s)) {
                    showLoadingDialog(s);
                } else {
                    hideLoadingDialog();
                }
            }
        });
    }

    private KProgressHUD pDialog;

    public void showLoadingDialog(String title) {
        if (pDialog == null) {
            pDialog = KProgressHUD.create(Objects.requireNonNull(getContext()))
                    .setStyle(KProgressHUD.Style.SPIN_INDETERMINATE)
                    .setLabel("Please wait")
                    .show();
        }

        if (!pDialog.isShowing()) {
            pDialog.setLabel(TextUtils.isEmpty(title) ? "Loading..." : title);
            pDialog.show();
        }
    }

    public void hideLoadingDialog() {
        if (pDialog != null && pDialog.isShowing()) {
            pDialog.dismiss();
        }
    }

    @Override
    public void onDestroyView() {
        hideLoadingDialog();
        super.onDestroyView();
    }
}
